package com.generic.mybatis.dal.interceptor.automap;

import org.apache.ibatis.type.JdbcType;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 字段映射类，用于描述java对象字段和数据库表字段之间的对应关系
 */
public class FieldMapper {

    private static final ThreadLocal<AtomicInteger> index = ThreadLocal.withInitial(() -> new AtomicInteger(0));

    private final TableMapper tableMapper;

    private Field field;

    /**
     * Java对象字段名
     */
    private String fieldName;

    /**
     * 数据库表字段名
     */
    private String dbFieldName;

    /**
     * 数据库字段对应的jdbc类型
     */
    private JdbcType jdbcType;

    public FieldMapper(TableMapper tableMapper) {
        this.tableMapper = tableMapper;
    }

    public String getDbFieldName() {
        return dbFieldName;
    }

    public void setDbFieldName(String dbFieldName) {
        this.dbFieldName = dbFieldName;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public JdbcType getJdbcType() {
        return jdbcType;
    }

    public void setJdbcType(JdbcType jdbcType) {
        this.jdbcType = jdbcType;
    }

    public Field getField() {
        return field;
    }

    public void setField(Field field) {
        this.field = field;
    }

    public String getAlias() {
        // 表用双下划线分隔
        return String.format("%s__%s", tableMapper.getAlias(), dbFieldName);
    }

    public String getParameterName() {
        int newValue = index.get().incrementAndGet();
        if (newValue >= 1000) {
            index.set(new AtomicInteger(0));
        }
        return fieldName + "_" + newValue;
    }
}
